<?php

//    (c) 2011 Donders Centre/Simon Oosthoek
//
//    This file is part of PIM.
//
//    PIM is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 2 of the License, or
//    (at your option) any later version.
//
//    PIM is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with PIM.  If not, see <http://www.gnu.org/licenses/>.
//
$pim_dir="/home/common/Services/pim";
$ganglia_baseurl="http://ganglia.fcdonders.nl";
$pim_datadir="$pim_dir/data";
$pim_actdir="$pim_dir/pidaction";
$pim_confdir="$pim_dir/config";

/* ============================================================*/
/* start of function definitions                               *
/* ============================================================*/

/* Function __json_encode() to encode arrays as json string
   post PHP 5.2.x, this function can be replaced by a native function (json_encode)
 */
function __json_encode( $data ) {           
    if( is_array($data) || is_object($data) ) {
        $islist = is_array($data) && ( empty($data) || array_keys($data) === range(0,count($data)-1) );
       
        if( $islist ) {
            $json = '[' . implode(',', array_map('__json_encode', $data) ) . ']';
        } else {
            $items = Array();
            foreach( $data as $key => $value ) {
                $items[] = __json_encode("$key") . ':' . __json_encode($value);
            }
            $json = '{' . implode(',', $items) . '}';
        }
    } elseif( is_string($data) ) {
        # Escape non-printable or Non-ASCII characters.
        $string = '"' . addcslashes($data, "\"\\\n\r\t\f/" . chr(8)) . '"';
        $json    = '';
        $len    = strlen($string);
        # Convert UTF-8 to Hexadecimal Codepoints.
        for( $i = 0; $i < $len; $i++ ) {
           
            $char = $string[$i];
            $c1 = ord($char);
           
            # Single byte;
            if( $c1 <128 ) {
                $json .= ($c1 > 31) ? $char : sprintf("\\u%04x", $c1);
                continue;
            }
           
            # Double byte
            $c2 = ord($string[++$i]);
            if ( ($c1 & 32) === 0 ) {
                $json .= sprintf("\\u%04x", ($c1 - 192) * 64 + $c2 - 128);
                continue;
            }
           
            # Triple
            $c3 = ord($string[++$i]);
            if( ($c1 & 16) === 0 ) {
                $json .= sprintf("\\u%04x", (($c1 - 224) <<12) + (($c2 - 128) << 6) + ($c3 - 128));
                continue;
            }
               
            # Quadruple
            $c4 = ord($string[++$i]);
            if( ($c1 & 8 ) === 0 ) {
                $u = (($c1 & 15) << 2) + (($c2>>4) & 3) - 1;
           
                $w1 = (54<<10) + ($u<<6) + (($c2 & 15) << 2) + (($c3>>4) & 3);
                $w2 = (55<<10) + (($c3 & 15)<<6) + ($c4-128);
                $json .= sprintf("\\u%04x\\u%04x", $w1, $w2);
            }
        }
    } else {
        # int, floats, bools, null
        $json = strtolower(var_export( $data, true ));
    }
    return $json;
} 

function elapsed_to_human($elap) {
	$elapar = preg_split("/-|:/", $elap);
	if (count($elapar) == 2) {
		//mins:secs
		return $elap . " min:sec";
	} else if (count($elapar) == 3) {
		//hours:mins:secs
		return $elap . " hrs:min:sec";
	} else if (count($elapar) == 4) {
		//days-hours:mins:secs
		$days=array_shift($elapar);
		return "$days days and " . implode(":", $elapar) . " hrs:min:sec";
	}

}

function pid_data($filename) {
	global $pim_datadir;
	if (!file_exists($filename)) {
		return array();
	}

	$data = file($filename);
	$pidhistory = array();
	$category = "header";
	$timestamp=0;
	foreach($data as $row) {
		// strip whitespace from beginning and end of the line
		$row = trim($row);
		
		// skip empty lines
		if (empty($row)) {
			continue;
		}

		list($key,$value) = explode("=", $row);
		// remove quotes from value
		$value = str_replace('"', '', $value);

		// store values by keyname, just what the shell would see
		// when sourcing the file
		$pidhistory['shellview'][$key] = $value;

                if ($key == "pid_notified" || $key=="pid_randval" ) {
                       // store notification values under a different category
                        $pidhistory['notify'][] = array($key, $value);
			$pidhistory['notify'][$key]=$value;
//		       echo "<!-- " ;
//		       print_r($pidhistory['notify']);
//		       echo "-->\n"renewed;
                } else if ( $timestamp > 0 ) {
			if ($key == 'pid_timestamp') {
				$timestamp = $value;
				$pidhistory[$category][$timestamp] = array('humantimestamp' => strftime('%F %R', $timestamp), 'timestamp' => $timestamp);
			} else if ( preg_match("/^pid_renewed/", $key) ) {
				$pidhistory[$key][] = $value;
			} else {
				$pidhistory[$category][$timestamp][$key] = $value;
				// keep track of the elapsed time in the header
				if ( $key == "pid_elapsedtime" ) {
					$pidhistory['header'][$key] = $value;
				}
			}
		} else {
			if ($key == 'pid_timestamp') {
				$category = "samples";
				$timestamp = $value;
				$pidhistory[$category][$timestamp] = array('humantimestamp' => strftime('%F %R', $timestamp), 'timestamp' => $timestamp);
			} else {
				$pidhistory[$category][$key] = $value;
			}
		}
			
	}
	if (file_exists($pidhistory['header']['pid_configused']))  {
		$fname= $pidhistory['header']['pid_configused'];
		$data = file($fname);
		foreach ($data as $row) {
			// strip whitespace from beginning and end of the line
			$row = trim($row);
			
			// skip empty lines or commented lines
			if (empty($row) or preg_match("/^\s*#/", $row) ) {
				continue;
			}

			//get the variable+value:
			list($key,$value) = explode("=", $row);
			// remove quotes from value
			$value = str_replace('"', '', $value);
			$pidhistory['config'][$key]=$value;
		}

	}

	return $pidhistory;
}

function grepvar($pidfile, $varname) {
	$line=exec("grep --max-count=1 '^$varname' $pidfile", $all_lines, $exitcode);
	if ($exitcode == 0) {
		$line=trim($line);
		list($key,$val)=explode('=',$line);
		$val = str_replace('"', '', $val);
		return $val;
	} else {
		return "null";
	}
}

function pim_link() {
	return "http://pim/";
}

function process_link($host, $pid) {
	return pim_link() . "?" . "host=$host" . "&" . "pid=$pid";
}

function host_link($host, $user="") {
	$link = pim_link() . "?" . "host=$host";
	if (strlen($user) > 0) {
		$link .= "&" . "user=$user";
	}
	return $link;
}

function fancy_host_link($host) {
	return '<a href="' . host_link($host) .'">' . $host . '</a>' . ganglia_link($host);
}

function user_link($user) {
	return pim_link() . '?' . "user=$user";
}

function contact_link($user) {
	return "https://intranet.donders.ru.nl/floormaps/?searchstring=$user";
}

function fancy_user_link($user) {
	global $fullname;
	$outstr = '<a href="' . user_link($user) . '">' . $fullname[$user] . '</a> ';
	$outstr .= '<a href="' . projectdb_link($user) . '"><img src="img/projects-icon.png" alt="projectdb"></a> ';
	$outstr .= '<a href="' . contact_link($user) . '"><img src="img/phone-icon.png" alt="contact"></a> ';
	return $outstr;
}

function projectdb_img($user) {
	return "http://projects.fcdonders.nl/app/webroot/img/staff/thumbs-intranet/$user.jpg";
}

function projectdb_link($user) {
	return "http://projects.fcdonders.nl/index.php/users/view/$user";
}

function ganglia_url($host) {
	global $ganglia_baseurl;
	return "$ganglia_baseurl/?c=Mentat+Cluster&h=$host";
}
function ganglia_link($host) {
 	return '<a title="View ' .$host. ' in ganglia" target="_blank" href="' .ganglia_url($host).'"><img src="img/ganglia_icon.png" /></a>';
}

function ganglia_loadone($host) {
	global $ganglia_baseurl;
	return "$ganglia_baseurl/graph.php?g=load_report&z=small&c=Mentat%20Cluster&h=$host";
}

function ganglia_memreport($host) {
	global $ganglia_baseurl;
	return "$ganglia_baseurl/graph.php?g=mem_report&z=small&c=Mentat%20Cluster&h=$host";
}

function change_title($newtitle) {
	echo '<script type="text/javascript">' ."\n";
	echo "	document.title = \"$newtitle\";\n";
	echo '</script>' . "\n";
}

function get_proctype($host, $pid) {
	global $pim_datadir;
	$filenm="$pim_datadir/${host}_$pid";
	if (file_exists($filenm)) {
		$cmdline=grepvar($filenm, "pid_cmdline");
		$bits=explode(" ", $cmdline);
		$chips=explode("/", $bits[0]);
		return end($chips);
	}
	return false;
}

// remove quotes for array_map
function remove_quotes($item) {
	return str_replace('"', '', $item);
}

function projectdb_getnames() {
	$rawfile=file_get_contents("http://projects.fcdonders.nl/index.php/reports/users.csv");
	if (strlen($rawfile) == 0) {
		return "null";
	} else {
		$csv_data=explode("\n", $rawfile);
		$header=trim(array_shift($csv_data));
		$cols=explode(";", $header);
		$cols=array_map('remove_quotes',$cols);
		$idcol=array_search("id", $cols);
		$fncol=array_search("firstName", $cols);
		$mncol=array_search("middleName", $cols);
		$lncol=array_search("lastName", $cols);
		foreach ($csv_data as $line) {
			$line=trim($line);
			$cols=explode(";", $line);
			$cols=array_map('remove_quotes', $cols);
			$fullname[$cols[$idcol]]=$cols[$fncol];
			if (strlen($cols[$mncol]) > 0) {
				$fullname[$cols[$idcol]] .= " " . $cols[$mncol];
			}
			$fullname[$cols[$idcol]] .= " " . $cols[$lncol];
		}
		return $fullname;
	}
}

function exclude_user ($user) {
	global $pim_confdir;
	if (file_exists("$pim_confdir/pim_vacation")) {
		$line=exec("grep --max-count=1 '^$user' $pim_confdir/pim_vacation", $all_lines, $exitcode);
		if ($exitcode == 0) {
			return true;
		}
	}
	return false;
}
